package uvsq.acsis.projects.xml.DB;

import java.io.IOException;
import java.util.List;

import javax.xml.bind.JAXBException;

import org.apache.log4j.Logger;

import uvsq.acsis.projects.xml.model.Book;
import uvsq.acsis.projects.xml.model.Books;
import uvsq.acsis.projects.xml.model.ObjectFactory;
import uvsq.acsis.projects.xml.parsers.XSLTProcessor;
import uvsq.acsis.projects.xml.util.Marshaller;
import uvsq.acsis.projects.xml.util.QueryHelper;
import uvsq.acsis.projects.xml.util.XmlHelper;

public class DB {

	private static final Logger log = Logger.getLogger(DB.class);
	private static ObjectFactory fatc = new ObjectFactory();
	
	private static String BOOKS_DB_FILE = "/opt/stadies/workspaces/acsis-xml/xml/src/main/resources/books-db.xml";
	
	@SuppressWarnings("restriction")
	public static String getBooForTitle(String titre){
		
		String bStr = QueryHelper.xPathAsNodeListString("//book[contains(title, '"+ titre +"')]", BOOKS_DB_FILE);
		
		log.debug(bStr);
		
		bStr = XmlHelper.addWrap(bStr, "books");
		
		//get from internet
		if(bStr == null || bStr.equals("")){
			
			log.debug("books not fount in database");
			
			bStr = XSLTProcessor.process("https://isbndb.com/api/books.xml?access_key=32XXE236&index1=title&value1=" + titre, "/opt/stadies/workspaces/acsis-xml/xml/src/main/java/uvsq/acsis/projects/xml/parsers/isbnConverter.xslt");
			log.debug("books fount in remote database");
		}
		
		Books books = fatc.createBooks();
		try {
			books = Marshaller.writeJAXBObject(books, bStr);
			String booksStr = Marshaller.writeJAXBString(books);
			
			log.debug(booksStr);
			
			XmlHelper.appendXmlFile(BOOKS_DB_FILE, booksStr);
			
			return booksStr;
			
		} catch (JAXBException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
}
